package cloud.misiro.spring.cloud.discovery;

import cloud.misiro.spring.cloud.MiniDiscoveryProperties;
import cloud.misiro.spring.cloud.MiniServiceInstance;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MiniDiscoveryClient implements DiscoveryClient {

    private static final Logger logger = LoggerFactory.getLogger(MiniDiscoveryClient.class);

    private final MiniDiscoveryProperties miniDiscoveryProperties;

    public MiniDiscoveryClient(MiniDiscoveryProperties miniDiscoveryProperties) {
        this.miniDiscoveryProperties = miniDiscoveryProperties;
    }

    @Override
    public List<ServiceInstance> getInstances(String serviceId) {
        Map<String, Object> param = new HashMap<>();
        param.put("serviceName", serviceId);

        String response = HttpUtil.get(miniDiscoveryProperties.getServerAddr() + "/list", param);
        return JSON.parseArray(response).stream().map(hostInfo -> {
            MiniServiceInstance miniServiceInstance = new MiniServiceInstance();
            miniServiceInstance.setServiceId(serviceId);
            String ip = ((JSONObject) hostInfo).getString("ip");
            Integer port = ((JSONObject) hostInfo).getInteger("port");
            miniServiceInstance.setHost(ip);
            miniServiceInstance.setPort(port);
            return miniServiceInstance;
        }).collect(Collectors.toList());
    }

    @Override
    public List<String> getServices() {
        String response = HttpUtil.post(miniDiscoveryProperties.getServerAddr() + "/listServiceNames", new HashMap<>());
        logger.info("query service instance list, response: {}", response);
        return JSON.parseArray(response, String.class);
    }

    @Override
    public String description() {
        return "Spring Cloud Mini Discovery Client";
    }
}
